package com.richinfo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.richinfo.common.config.Global;
import com.richinfo.controller.SysuserController;
import com.richinfo.entity.LoginToken;
import com.richinfo.entity.TbAppsTodo;
import com.richinfo.entity.query.AppsTodoQuery;
import com.richinfo.mapper.TbAppsTodoMapper;
import com.richinfo.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Service
public class TbAppsTodoService {

    private static Logger logger = Logger.getLogger(TbAppsTodoService.class);

    @Autowired
    private TbAppsTodoMapper tbAppsTodoMapper;

    @Autowired
    private LoginTokenService loginTokenService;

    public List sendTodoToSms(String loginName, List mobiles, String signature,String timeStamp,String nonce) {
        List results=new ArrayList();
        String reqResult = "";
        try {
            List<TbAppsTodo> todoList = tbAppsTodoMapper.getListTodo(loginName);
            logger.info("查询数据查到的todoList：" + todoList);
            for (TbAppsTodo todo : todoList) {
                String thirdUrl = todo.getUrl();
                //替换第三方的真实地址，改为e掌通公网地址
                String url = replaceDomainAndPort(Global.getConfig("externalIp"), Global.getConfig("externalPort"), thirdUrl);
                //对地址进行Unicode
                String gotoUrl = URLEncoder.encode(url, "UTF-8");
               /*
                Map<String,Object> maps = new HashMap<>();
                maps.put("url","http://hfx.net/emessage/sms/jumbThird?gotoUrl="+gotoUrl);
                maps.put("appName",todo.getAppName());
                maps.put("content",todo.getContent());
                maps.put("parentowner",todo.getParentowner());
                maps.put("create",todo.getCreatetime());
                maps.put("processor",todo.getProcessor());*/
                //拼接发送短信接口请求参数--参数placeHolderContent

            /*  JSONObject json=new JSONObject();
                json.put("url", Global.getConfig("smsToThirdUrl")+gotoUrl);
                json.put("parentowner",todo.getParentowner());
                json.put("appName",todo.getAppName());
                json.put("content",todo.getContent());
                json.put("parentowner",todo.getParentowner());
                json.put("create",todo.getCreatetime());
                json.put("processor",todo.getProcessor());
                Map encryptMap=new HashMap();
                encryptMap.put("placeHolderContent",json);
                //接收方手机号码
                encryptMap.put("mobiles",mobiles);
                //模板id，每个商户独立申请使用，请联系业务接口人获取
                encryptMap.put("templateId",Global.getConfig("templateId"));
                JSONObject encryptJson = JSONObject.fromObject(encryptMap);*/

                /**************调用生成转短url接口 redirectUrl/convertShortUrl 加密参数拼接 start*******************/
                JSONObject json = new JSONObject();
                json.put("srcUrl", Global.getConfig("smsToThirdUrl")+gotoUrl);
                json.put("templateId", Global.getConfig("templateId"));
                //json.put("mobile",mobiles);
                logger.info("**********encrypt加密前参数*************：" + json);
                /******************** end *************/
                String encrypt = AESEncryptUtil.aesEncrypt(json.toString(), AESEncryptUtil.getAESKey(Global.getConfig("secretKey")));
                logger.info("encrypt加密后：" + encrypt + "--加密密钥：" + Global.getConfig("secretKey"));
                //请求参数 secretId调用方id
                String secretId = Global.getConfig("secretId");
                JSONObject maps = new JSONObject();
                maps.put("encrypt", encrypt);
                maps.put("timeStamp", timeStamp);
                maps.put("nonce", nonce);
                maps.put("secretId", secretId);
                maps.put("signature", signature);
                //调用发送短信接口
                logger.info("调用发送短信请求参数maps：" + maps);
                //调用生成转短url
                reqResult = reqConvertShortUrl(maps.toString());
                if(StringUtils.isNotBlank(reqResult)){
                    logger.info("调用转短url请求返回的数据："+reqResult);
                    JSONObject jsonObject = JSONObject.fromObject(reqResult);
                    String resCode=jsonObject.getJSONObject("resStatus").getString("resCode");
                    if(TokenValidateExceptionCodeEnum.Success.code().equals(resCode)){
                        String shortUrl=jsonObject.getString("result");
                        logger.info("返回加密结果："+shortUrl);
                        String decryptUrl=AESEncryptUtil.aesDecrypt(shortUrl,AESEncryptUtil.getAESKey(Global.getConfig("secretKey")));
                        results.add(decryptUrl);
                    }else{
                        logger.info("调用转短接口出错："+jsonObject);
                    }
                }


                //请求发送短信接口
                //reqResult=sendSmsByMobiles(maps);

            /*    if(StringUtils.isNotBlank(reqResult)){
                    JSONObject jsonObject = JSONObject.fromObject(reqResult);
                    String resCode=jsonObject.getJSONObject("resStatus").getString("resCode");
                    if(TokenValidateExceptionCodeEnum.Success.code().equals(resCode)){
                        Map<String,Object> resultMap = new HashMap<>();
                        resultMap.put(Constant.STATUS, Constant.SUCCESS);
                        resultMap.put(Constant.MSG, RespCodeEnum.SUCCESS.getDesc());
                        result.add(resultMap);
                    }
                }*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    public List converShortUrlByParams(String url,String signature,String timeStamp,String nonce){
        String reqResult = "";
        List results=new ArrayList();
        try{
            /**************调用生成转短url接口 redirectUrl/convertShortUrl 加密参数拼接 start*******************/
            JSONObject json = new JSONObject();
            String gotoUrl = URLEncoder.encode(url, "UTF-8");
            logger.info("**********URLEncoder --- gotoUrl*************：" + gotoUrl);
            json.put("srcUrl", Global.getConfig("smsToThirdUrl")+gotoUrl);
            logger.info("**********srcUrl*************：" + Global.getConfig("smsToThirdUrl")+gotoUrl);
            json.put("templateId", Global.getConfig("templateId"));
            //json.put("mobile",mobiles);
            logger.info("**********encrypt加密前参数*************：" + json);
            /******************** end *************/
            String encrypt = AESEncryptUtil.aesEncrypt(json.toString(), AESEncryptUtil.getAESKey(Global.getConfig("secretKey")));
            logger.info("encrypt加密后：" + encrypt + "--加密密钥：" + Global.getConfig("secretKey"));
            //请求参数 secretId调用方id
            String secretId = Global.getConfig("secretId");
            JSONObject maps = new JSONObject();
            maps.put("encrypt", encrypt);
            maps.put("timeStamp", timeStamp);
            maps.put("nonce", nonce);
            maps.put("secretId", secretId);
            maps.put("signature", signature);
            //调用发送短信接口
            logger.info("调用发送短信请求参数maps：" + maps);
            //调用生成转短url
            reqResult = reqConvertShortUrl(maps.toString());
            if(StringUtils.isNotBlank(reqResult)){
                logger.info("调用转短url请求返回的数据："+reqResult);
                JSONObject jsonObject = JSONObject.fromObject(reqResult);
                String resCode=jsonObject.getJSONObject("resStatus").getString("resCode");
                if(TokenValidateExceptionCodeEnum.Success.code().equals(resCode)){
                    String shortUrl=jsonObject.getString("result");
                    logger.info("返回加密结果："+shortUrl);
                    String decryptUrl=AESEncryptUtil.aesDecrypt(shortUrl,AESEncryptUtil.getAESKey(Global.getConfig("secretKey")));
                    results.add(decryptUrl);
                }else{
                    logger.info("调用转短接口出错："+jsonObject);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return results;
    }

    public String reqConvertShortUrl(String mapParam) {
        String reqResult = null;
        try {
            String reqShortUrl = Global.getConfig("reqShortUrl");
            reqResult = HttpUtils.post(reqShortUrl, mapParam);
            logger.info("请求地址：" + reqShortUrl + "******请求参数：" + mapParam + "请求短信小程序生成转短url接口返回的结果：" + reqResult);
            if (StringUtils.isBlank(reqResult)) {
                logger.info("请求短信小程序生成转短url失败,请求地址url=：" + reqShortUrl + "请求参数mapParam=" + mapParam);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reqResult;
    }


    /**
     * 请求发送短信接口
     *
     * @param mapParam
     * @return
     */
    public String sendSmsByMobiles(String mapParam) {
        String reqResult="";
        try{
            String sendSmsUrl = Global.getConfig("sendSmsUrl");
            reqResult = HttpUtils.post(sendSmsUrl, mapParam);
            logger.info("请求发送短信接口返回的结果：" + reqResult);
            if (StringUtils.isBlank(reqResult)) {
                logger.info("请求发送短信接口失败,请求地址url=：" + sendSmsUrl + "请求参数mapParam=" + mapParam);
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return reqResult;
    }

    public static String getVerify(int length) {
        String code = "";
        String str = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASFGHJKLZXCVBNM";
        String[] strs = str.split("");
        for (int i = 0; i < length; i++) {
            code += strs[(int) (Math.random() * strs.length)];
        }
        return code;
    }

    public static String replaceDomainAndPort(String domain, String port, String url) {
        String url_bak = "";
        if (url.indexOf("//") != -1) {
            String[] splitTemp = url.split("//");
            url_bak = splitTemp[0] + "//";
            if (port != null) {
                url_bak = url_bak + domain + ":" + port;
            } else {
                url_bak = url_bak + domain;
            }

            if (splitTemp.length >= 1 && splitTemp[1].indexOf("/") != -1) {
                String[] urlTemp2 = splitTemp[1].split("/");
                if (urlTemp2.length > 1) {
                    for (int i = 1; i < urlTemp2.length; i++) {
                        url_bak = url_bak + "/" + urlTemp2[i];
                    }
                }
            }
        }
        return url_bak;
    }


    public static void main(String[] args) {
        String url = "http://imsp-test.gmcc.net/bpm/ssoToken.html?mytarget=tydbljdz&wf_docunid=8609cf34001b5043310ac5d0d006ebd10125&wf_taskid=cec572a00eb070431a092a50da44398bbcdf";
        String realUrl = replaceDomainAndPort("120.198.246.137", "18088", url);
        System.out.println("realUrl=" + realUrl);
    }

    public PageInfo<TbAppsTodo> query(AppsTodoQuery appsTodoQuery) {
        PageHelper.startPage(appsTodoQuery.getPage(), appsTodoQuery.getSize());
        //处理跳转连接
        List<TbAppsTodo> todoList = tbAppsTodoMapper.findAll(appsTodoQuery);
        String loginToken = loginTokenService.queryTokenByUserName(appsTodoQuery.getUserId());

        todoList.forEach(x->{
            String s = replaceDomainAndPort(Global.getConfig("externalIp"), Global.getConfig("externalPort"), x.getUrl());
            String realGotoUrl = "";
            if (s.contains(Global.getConfig("bpmSsoUrl"))) {
                realGotoUrl = s.replace(Global.getConfig("bpmSsoUrl"), Global.getConfig("realSsoUrl"));
                logger.info("替换后的url=" + realGotoUrl);
                x.setUrl(realGotoUrl+"&loginToken="+loginToken);
            }else{
                x.setUrl(s+"&loginToken="+loginToken);
            }
        });
        return new PageInfo<>(todoList);
    }
}
